<template>
  <view>
    <u-sticky>
      <u-navbar back-text=" " title="整改" :background="background" title-color="#ffffff" :custom-back="customBack" back-icon-color="#ffffff" ref="navbar" title-size="36"></u-navbar>
      <xmInfo
        :projectno="itemContent.projectno"
        :projectname="itemContent.projectname"
        ref="xmInfo"
        class="u-sticky"
      ></xmInfo>
    </u-sticky>
    <scroll-view
      class="scroll-list"
      scroll-y="true"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="triggered"
      @refresherrefresh="refresherrefresh"
      :style="{ height: computedScrollViewHeight }"
    >
    <view
        class="scroll-content"
        ref="scrollContent"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        :style="{ height: computedScrollViewHeight  }"
      >
        <view
          class="cu-item shadow"
          v-for="(item, index) in zhengGaiData"
          :key="item.id"
        >
			<view class="cu-form-group">
        <view class="title">
          <view style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;width: 40px;text-align: center;font-style: italic;font-weight: bold">
            {{ index + 1 }}
          </view>
        </view>
        <view style="flex: 1;" class="flex">
            <view class="text-xl text-bold title title1">{{ item.createtime }}</view>
            <view class="text-xl text-bold title" style="flex: 1;">{{ item.acceptor }}</view>
        </view>
			</view>

          <view class="cu-form-group">
            <view class="title">整改内容</view>
            <view style="flex: 1;">{{ item.rectificationcontent }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">整改期限</view>
            <view style="flex: 1;" class="title">{{ item.endtime }}</view>
          </view>
          <view class="cu-form-group">
            <view class="title">整改措施</view>
            <view style="flex: 1;">{{ item.rectificationmeasures }}</view>
          </view>
          <view class="cu-form-group">
            <view style=" display: inline-block;padding: 5px;background: #0081ff;color: #fff;text-align: center;font-style: italic;font-weight: bold">
                整改结果
              </view>
          </view>
          <!-- <view class="cu-form-group" style="min-height: 0"></view>
          <view class="cu-bar bg-white">
            <view class="action text-black">整改图片</view>
          </view>
          <view class="cu-form-group">
            <js-uploadfile
              v-if="uploadFlag"
              v-model="item.dataMap"
              maxCount="0"
              :biz-key="item.id"
              biz-type="rectList_file"
              :deletable="false" 
              customBtn="false"
            ></js-uploadfile>
          </view> -->
          
          <view class="cu-card">

            <view class="cu-form-group">
              <view class="title">整改结果</view>
              <view style="flex: 1;">{{ item.rectificationresult }}</view>
            </view>

            <view class="cu-form-group">
              <view class="title">整改日期</view>
              <view style="flex: 1;">{{ item.rectificationdate }}</view>
            </view>

          </view>
          <view class="cu-form-group">
            <view style=" display: inline-block;padding: 5px;background: #1cbbb4;color: #fff;text-align: center;font-style: italic;font-weight: bold">
                整改验收
              </view>
          </view>
          <view class="cu-card">
            <view class="cu-form-group justify-start">
              <view class="title">验收结果</view>
              <view>
                <view style="width: auto;">
                  <dictLabel
                    :value="item.checkresult ? item.checkresult : '0'"
                    :dict-list="dictList"
                  ></dictLabel>
                </view>
              </view>
            </view>
            <view class="cu-form-group">
              <view class="title">验收意见</view>
              <view style="flex: 1;">{{ item.checkopinion }}</view>
            </view>
            <view class="cu-form-group">
              <view class="title">验收时间</view>
              <view style="flex: 1;">{{ item.checkdate }}</view>
            </view>
          </view>
          
          <!-- <view class="cu-form-group" style="min-height: 0"></view>
          <view class="cu-bar bg-white">
            <view class="action text-black">完成图片</view>
          </view>
          <view class="cu-form-group">
            <view class="grid col-4 grid-square flex-sub">
              <view
                class="bg-img"
                v-for="(itemImg, index) in item.finishImgList"
                :key="index"
                @tap.stop="ViewImage(item.finishImgList, $event)"
                :data-url="item.finishImgList[index].url"
              >
                <image
                  :src="item.finishImgList[index].url"
                  mode="aspectFill"
                ></image>
                <view
                  class="cu-tag bg-red"
                  @tap.stop="DelImg"
                  :data-index="index"
                >
                </view>
              </view>
            </view>
          </view> -->
        
      <view class="cu-form-group justify-between" style="color:#3E97B0 ;">
        <view class="content-footer-right" @click="add(item)">查看详情</view>
		    <view class="justify-end">
          <button class="cu-btn lines-green shadow-blur" @click="add(item,'bUploadResult')" v-if="item.bresult&&resultflag">
          <text class="cuIcon-add"></text> 整改结果
        </button>
        <button class="cu-btn lines-green shadow-blur" @click="add(item,'bUploadAccept')" v-if="item.bcheck&&checkflag">
          <text class="cuIcon-add"></text> 整改验收
        </button>
        </view>
		  </view>
        </view>
      <!-- </view> -->
      <view v-if="zhengGaiData.length" class="loadmore">
        <u-loadmore :status="loadStatus"></u-loadmore>
      </view>
      <u-empty v-if="!zhengGaiData.length" style="height: 100%;"></u-empty>
      </view>
    </scroll-view>

    <!-- <view style="height: 80px" v-if="status != vuex_config.zgStatus"></view>
    <view class="btn-group cu-bar foot" style="height: 80px" v-if="status != vuex_config.zgStatus">
      <button class="cu-btn bg-green shadow-blur" @click="add()">
        <text class="cuIcon-add"></text> 上传
      </button>
    </view> -->
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import dictLabel from "@/pages/zfgs/index/componetns/dictLabel.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo ,dictLabel},
  data() {
    return {
      background:{
        backgroundColor: '#3E97B0',
      },
      uploadFlag: true,
      triggered: false,
      loadStatus: "loadmore",
      query: {
        pageNo: 1,
        pageSize: 20,
      },
      itemContent: {},
      zhengGaiData: [],
      resultflag: hasPermission('app:btn:result:zhenggai'),
      checkflag: hasPermission('app:btn:check:zhenggai'),
      status:'',
      scrollViewHeight: 0,
      headerHeight: 0,
      dictList: [],
    };
  },
  onShow() {
    this.uploadFlag = true;
    this.query.pageNo = 1;
    this.loadList();
  },
  onLoad(e) {
    
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        this.query.projectno = this.itemContent.projectno;
        console.log(this.itemContent);
        this.status = e.status
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
    this.getDictList();
  },
  mounted() {
    this.$refs.xmInfo.$on('child-mounted-done', () => {
      this.calculateScrollViewHeight();
    });
  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
    },
  },
  methods: {
    getDictList() {
      this.$u.api.dictListData({ dictType: "zf_check_result" }).then((res) => {
        this.dictList = res;
      });
    },
    customBack(){
      // 跳转到工作台页面
      // uni.navigateTo({
      //   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
      // });
	  uni.navigateBack({
	    delta: 1,
	  });
    },
    async calculateScrollViewHeight() {
      try {
    // 等待头部高度计算完成
          await new Promise((resolve) => {
            this.$nextTick(() => {
              this.headerHeight = this.$refs.xmInfo.$refs['u-sticky'].height + this.$refs.xmInfo.$refs['u-sticky'].h5NavHeight + this.$refs.navbar.navbarHeight;
              resolve();
            });
          });
          // 计算tabBar高度
    //       if(this.status != this.vuex_config.zgStatus){
    //         this.tabBarHeight = 90;
    //       }else{
    //         this.tabBarHeight = 0;
    //       }
    this.tabBarHeight = 0
          // 获取屏幕高度
          const systemInfo = uni.getSystemInfoSync();
          const screenHeight = systemInfo.windowHeight;
          // 计算scroll-view高度
          this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
      } catch (error) {
        console.error('Error while calculating ScrollView height:', error);
      }
    },
    async refresherrefresh() {
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadList();
      const scrollTop = 0
      uni.pageScrollTo({
            scrollTop,
            duration: 0,
      });
      setTimeout(() => {
        this.triggered = false;
      }, 500);
    },
    loadList(type) {
      this.$u.api.zfgs.zgListData(this.query).then((res) => {
        if (res.list.length < 20 || res.list.length == 0) {
          this.loadStatus = "nomore";
        }
        var list = res.list;
        if (type == "add") {
          for (var i = 0; i < list.length; i++) {
            this.zhengGaiData.push(list[i]);
          }
        } else {
          this.zhengGaiData = list;
        }
        // 遍历zhengGaiData,把每一项的zhengGaiData的createtime 格式化年月日
        this.zhengGaiData.forEach((item) => {
          item.createtime = this.fmtDate(item.createtime)
        });
      });
    },
    fmtDate(date){
      // 格式化年月日
      var date = new Date(date);
      var date = new Date(date);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();
      return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
    },
    loadMore() {
      this.loadStatus = "loading";
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadList("add");
      }, 100);
    },

    add(item,name) {
      console.log(!item,'item===',name);
      this.uploadFlag = false;

      console.log(item,'item===',!!item);
      if (!!item) {
        if(name == 'bUploadResult'){
          // 整改结果
          uni.navigateTo({
            url: "/pages/zfgs/proj/zg/pmRectification/resultForm?id=" + item.id + "&status=" + this.status,
          });
        }else if(name == 'bUploadAccept'){
          uni.navigateTo({
            url: "/pages/zfgs/proj/zg/pmRectification/acceptForm?id=" + item.id + "&status=" + this.status,
          });
        }else{
          uni.navigateTo({
            url: "/pages/zfgs/proj/zg/pmRectification/form?id=" + item.id + "&status=" + this.status,
          });
        }

      } else {
        let obj = {
          projectno: this.itemContent.projectno,
          projectname: this.itemContent.projectname,
        };
        uni.navigateTo({
          url:
            "/pages/zfgs/proj/zg/pmRectification/form?item=" +
            JSON.stringify(obj) + "&status=" + this.status,
        });
      }
    },
    ViewImage(imageList, e) {
      // 阻止冒泡
      const url = imageList.map((item) => item.url);
      e.stopPropagation();
      uni.previewImage({
        urls: url,
        current: e.currentTarget.dataset.url,
      });
    },
  },
  beforeDestroy() {
    // 清理事件监听器
    try {
       this.$refs.xmInfo.$off('child-mounted-done');
     } catch (e) {
       console.log('Error while unbinding event:', e);
     }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .u-progress.data-v-0d33af60 {
  display: none;
}
.title {
  width: 110px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
}
.title {
  flex-shrink: 0;
}
.grid-square {
  margin-bottom: 0 !important;
}
.cu-card{
  border: 1px solid #0081ff;
}
.title1{
  width: 120px;
}
</style>